package com.max.sportmanage.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: java-sport-manage
 * @description:token工具类，生成token
 * @author: max-qaq
 * @create: 2021-10-21 12:18
 **/
@Slf4j
@Component
public class TokenUitl {

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    /**
     *
     * @param userDetails 传入用户登录信息 生成令牌
     * @return
     */
    public String generateToken(UserDetails userDetails){
        Map<String,Object> map = new HashMap<>(2);
        map.put("username",userDetails.getUsername());
        map.put("created",new Date());
        log.info("tokenuitl生成token");
        return generate(map);
    }

    /**
     *
     */
    public String generate(Map<String,Object> map){
        return Jwts.builder()
                .setClaims(map)
                .signWith(SignatureAlgorithm.HS512,secret)
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .compact();
    }

    /**
     * 根据token获取荷载信息
     * 如果过期返回null
     * @param token
     * @return
     */
    public Claims getTokenBody(String token){
        try{
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            return null;
        }

    }

    /**
     * 根据token得到用户名
     * @param token
     * @return
     */

    public String getUserNameByToken(String token){
        return (String) this.getTokenBody(token).get("username");
    }

    /**
     * 判断是否过期
     */
    public boolean isExpiration(String token){
        return this.getTokenBody(token).getExpiration().before(new Date());
    }

    public String refreshToken(String token){
        Claims claims = this.getTokenBody(token);
        claims.setExpiration(new Date());
        return this.generate(claims);//claims负载信息也是map
    }
}
